package model

import (
	"database/sql"
	"errors"
	_ "github.com/go-sql-driver/mysql"
)

type UserPO struct {
	ID int
	Nickname string
	Password string
}

type UserProfile struct {
	Name string
	Sex int
	Birthday int
}

type User struct {
	err error
	Data UserPO
	Profile UserProfile
}

func (u *User) Error() error {
	return u.err
}

func Register(nickname string, password string) (*User, error) {
	data := &UserPO{
		Nickname:nickname,
		Password:password,
	}
	if res, err := db.Exec("INSERT INTO `user` VALUES (NULL, ?, ?)", nickname, password); err != nil {
		return nil, err
	} else if id, err := res.LastInsertId(); err != nil {
		return nil, err
	} else {
		data.ID = int(id)
		return &User{Data:*data,}, nil
	}
}

func Login(id int, passwod string) (*User, error) {
	data := &UserPO{}
	db, err := sql.Open("mysql","root:LsqWSxQt@tcp(120.27.70.63:3306)/pwas?charset=utf8")
	if err != nil {
		return nil, err
	}
	row := db.QueryRow("SELECT * FROM `user` WHERE `id` = ?", id)
	err = row.Scan(&data.ID, &data.Nickname, &data.Password)
	if err != nil {
		return nil, err
	}
	if data.Password != passwod {
		return nil, errors.New("密码错误")
	}
	return &User{Data:*data}, nil
}

func LoadUser(id int, profile bool) *User {
	return &User{
		Data:UserPO{},
		Profile:UserProfile{},
	}
}

func (u *User) LoadProfile() *User {
	u.Profile = UserProfile{}
	return u
}

func (u *User) SaveProfile() *User {
	// TODO 保存数据
	return u
}
